package com.ctrip.demo.leetcode;

import java.util.*;

public class LeetCode539 {

    public static void main(String[] args) {
        // ["05:31","22:08","00:35"]
        ArrayList<String> strings = new ArrayList<>();
        strings.add("00:00");
        strings.add("23:59");
        System.out.println(findMinDifference2(strings));
    }

    public static int findMinDifference1(List<String> timePoints) {
        int n = timePoints.size() * 2;
        int[] nums = new int[n];
        for (int i = 0, idx = 0; i < n / 2; i++, idx += 2) {
            String[] split = timePoints.get(i).split(":");
            int h = Integer.parseInt(split[0]), m = Integer.parseInt(split[1]);
            nums[idx] = h * 60 + m;
            nums[idx + 1] = nums[idx] + 1440;
        }
        Arrays.sort(nums);
        int ans = nums[1] - nums[0];
        for (int i = 0; i < n - 1; i++) {
            ans = Math.min(ans, nums[i + 1] - nums[i]);
        }
        return ans;
    }

    public static int findMinDifference2(List<String> timePoints) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < timePoints.size(); i++) {
            String[] split = timePoints.get(i).split(":");
            int h = Integer.parseInt(split[0]), m = Integer.parseInt(split[1]);
            list.add(h * 60 + m);
            list.add(h * 60 + m + 1440);
        }
        Collections.sort(list);
        int ans = list.get(1) - list.get(0);
        for (int i = 0; i < list.size() - 1; i++) {
            ans = Math.min(ans,list.get(i + 1) - list.get(i));
        }
        return ans;
    }


    public static int findMinDifference(List<String> timePoints) {
        Set<Integer> set = new TreeSet<>();
        for (String timePoint : timePoints) {
            String[] split = timePoint.split(":");
            // 当天该时间点值
            set.add(Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]));
            // 记录「下一天该时间点」对应值
            set.add(Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]) + 1440);
        }
        if (set.size() < 2 * timePoints.size()) {
            return 0;
        }
        int min = 1440, cur = 0, index = 0;
        Iterator<Integer> iterator = set.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (index == 0) {
                cur = next;
                index++;
                continue;
            }
            int value = next - cur;
            if (min > value) {
                min = value;
            }
            cur = next;
        }
        return min;
    }


}
